package us.sunrisemorning.douyuchat;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class MessageUtils {

	public static Message decode(String body) {
		Message result = new Message();
		String[] kvs = StringUtils.split(body, "/");
		for (String kv : kvs) {
			String[] temp = StringUtils.split(kv, "@=");
			if (temp.length > 1) {
				String key = unescape(temp[0]);
				String value = unescape(temp[1]);
				result.set(key, value);
			}
		}
		return result;
	}

	public static String encode(Message m) {
		StringBuffer sb = new StringBuffer();
		Map<String, String> data = m.getData();
		for (String key : data.keySet()) {
			String value = data.get(key);
			sb.append(escape(key));
			sb.append("@=");
			sb.append(escape(value));
			sb.append("/");
		}
		return sb.toString();
	}

	private static String unescape(String str) {
		String result = StringUtils.replaceAll(str, "@S", "/");
		result = StringUtils.replaceAll(str, "@A", "@");
		return result;
	}

	private static String escape(String str) {
		String result = StringUtils.replaceAll(str, "@", "@A");
		result = StringUtils.replaceAll(str, "/", "@S");
		return result;
	}
}
